/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package torrent;

import DownLoadFile.DownLoadFile;
import ListeningThread.ListeningThread;
import ReadTorrent.ReadTorrent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import requestDataPacket.requestData;


/**
 *
 * @author THANG
 */
public class Torrent {

    /**
     * @param args the command line arguments
     */
   public static String[] ReadFileName()
    {
        File folder = new File("D:\\HOAN CHINH\\Hoc Ky 2\\java\\torrent\\temp");
        String[] str = new String[folder.listFiles().length];
        int i =0;
        for (final File fileEntry : folder.listFiles()) 
        {
            str[i] = fileEntry.getName();
            i++;
        }
        return str;
    }
    public static File mergeFiles(String[] names, String str) {  
        try {  
            int n = names.length;
            File[] files = new File[n];  
            for (int i = 1; i <= n; i++) {  
                files[i-1] = new File("temp\\" +names[i-1]);  
            }  
  
  
            File outFile = new File("Temp1."+str);  
  
            FileOutputStream fileOS = new FileOutputStream(outFile);  
  
            for (int i = 0; i < n; i++) {  
                FileInputStream fileIS = new FileInputStream(files[i]);  
                byte[] data = new byte[(int) files[i].length()];  
                int count = fileIS.read(data);  
                fileOS.write(data);  
                fileIS.close();  
//                if (del) {  
//                    files[i].delete();  
//                }  
  
            }  
            fileOS.close();  
  
            return outFile;  
        } catch (Exception e) {  
            JOptionPane.showMessageDialog(null, "Error in Merge File \n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);  
        }  
        return null;  
    }
    public static void main(String[] args) throws SocketException, UnknownHostException {
        // TODO code application logic here
        
        ReadTorrent rd = new ReadTorrent();
        rd.ReadFile();
        new ListeningThread(1005).start();
        for (int i = 0; i<  rd.FileLength; i++)
        {
            new requestData(rd.FileName.get(i), "127.0.0.1",1005).start();
            
        }
        new DownLoadFile().start();
        mergeFiles(ReadFileName(),".jpg");
    }
}
